/**
 * Copyright 2018 jianggujin (www.jianggujin.com).
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jianggujin.modulelink.mvc.upload;

import java.lang.reflect.Constructor;
import java.util.List;

import com.jianggujin.modulelink.util.JAssert;
import com.jianggujin.modulelink.util.JLogFactory;
import com.jianggujin.modulelink.util.JLogFactory.JLog;
import com.jianggujin.modulelink.util.JMultiValueMap;

/**
 * {@link JMultipartResolver}工厂
 * 
 * @author jianggujin
 *
 */
public class JMultipartResolverFactory {
   private static Constructor<? extends JMultipartResolver> multipartResolverConstructor;
   private static JMultipartResolverConfig multipartResolverConfig = new JMultipartResolverConfig();
   protected static final JLog logger = JLogFactory.getLog(JMultipartResolverFactory.class);

   static {
      tryImplementation(new Runnable() {
         @Override
         public void run() {
            useApacheMultipartResolver();
         }
      });
      tryImplementation(new Runnable() {
         @Override
         public void run() {
            useCommonsMultipartResolver();
         }
      });
   }

   public static JMultipartResolver getMultipartResolver(JMultipartResolverConfig config) {
      if (multipartResolverConstructor == null) {
         throw new IllegalStateException("nou set multipart resolver.");
      }
      try {
         return multipartResolverConstructor.newInstance(config);
      } catch (Throwable t) {
         throw new JMultipartException("Error creating logger for logger " + logger + ".  Cause: " + t, t);
      }
   }

   public static void setMultipartResolverConfig(JMultipartResolverConfig multipartResolverConfig) {
      JAssert.checkNotNull(multipartResolverConfig, "multipartResolverConfig must not be null.");
      JMultipartResolverFactory.multipartResolverConfig = multipartResolverConfig;
   }

   public static JMultipartResolverConfig getMultipartResolverConfig() {
      return multipartResolverConfig;
   }

   public static void cleanupFileItems(JMultiValueMap<String, JMultipartFile> multipartFiles) {
      if (multipartFiles == null) {
         return;
      }
      for (List<JMultipartFile> files : multipartFiles.values()) {
         for (JMultipartFile file : files) {
            file.delete();
            if (logger.isDebugEnabled()) {
               logger.debug("Cleaning up multipart file [" + file.getName() + "] with original filename ["
                     + file.getOriginalFilename() + "]");
            }
         }
      }
   }

   public static synchronized void useMultipartResolver(Class<? extends JMultipartResolver> clazz) {
      setImplementation(clazz);
   }

   public static synchronized void useApacheMultipartResolver() {
      setImplementation(com.jianggujin.modulelink.mvc.upload.JApacheMultipartResolver.class);
   }

   public static synchronized void useCommonsMultipartResolver() {
      setImplementation(com.jianggujin.modulelink.mvc.upload.JCommonsMultipartResolver.class);
   }

   private static void tryImplementation(Runnable runnable) {
      if (multipartResolverConstructor == null) {
         try {
            runnable.run();
         } catch (Throwable t) {
            // ignore
         }
      }
   }

   private static void setImplementation(Class<? extends JMultipartResolver> implClass) {
      try {
         Constructor<? extends JMultipartResolver> candidate = implClass.getConstructor(JMultipartResolverConfig.class);
         multipartResolverConstructor = candidate;
         if (logger.isDebugEnabled()) {
            logger.debug("JMultipartResolver initialized using '" + implClass + "' adapter.");
         }
      } catch (Throwable t) {
         throw new JMultipartException("Error setting Log implementation. Cause: " + t, t);
      }
   }
}
